//
//  ECUIVC_CDetailPage.m
//  Edu_iOS2018
//
//  Created by yanyan on 2018/1/17.
//  Copyright © 2018年 yanyan. All rights reserved.
//

#import "ECUIVC_CDetailPage.h"
#import "ECUITVCell_DetailMaterial.h"
#import "UIView_Helper.h"
#import "CYDataHelper.h"
extern CGFloat TABBAR_FOOTER_HEIGHT;
@interface ECUITVCell_CDetail()
@property(nonatomic,strong)UILabel *titleLabel;//课程名字
@property(nonatomic,strong)UILabel *numLabel;// 课程购买人数
@property(nonatomic,strong)UILabel *teacherLabel;//授课老师
@property(nonatomic,strong)UILabel *expiryDayLabel;//有效期天数
@property(nonatomic,strong)UILabel *detailLabel;//课程简介
@end
@implementation ECUITVCell_CDetail
- (void)addSubviews
{
    [super addSubviews];
    _titleLabel = [UIView_Helper yLabel];
    _titleLabel.font = [UIFont systemFontOfSize:18];
    _titleLabel.textColor = [UIColor colorWithHexString:@"#454545"];
    _titleLabel.numberOfLines = 0;
    [self.contentView addSubview:_titleLabel];
    
    _numLabel = [self labelForSomeDetail];
    [self.contentView addSubview:_numLabel];
    _teacherLabel = [self labelForSomeDetail];
    [self.contentView addSubview:_teacherLabel];
    _expiryDayLabel = [self labelForSomeDetail];
    [self.contentView addSubview:_expiryDayLabel];
    _detailLabel = [self labelForSomeDetail];
    _detailLabel.numberOfLines = 0;
    [self.contentView addSubview:_detailLabel];
    CGFloat hPadding = 10;
    CGFloat vPadding = 18;
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.contentView).offset(hPadding);
        make.top.equalTo(self.contentView).offset(vPadding);
        make.right.equalTo(self.contentView).offset(-hPadding);
        
    }];
    [self.numLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.titleLabel);
        make.top.equalTo(self.titleLabel.mas_bottom).offset(hPadding);
//        make.width.equalTo(self.titleLabel).multipliedBy(1/3.0);
        make.width.equalTo(self.teacherLabel);
        make.height.equalTo(@(20));
    }];
    [self.teacherLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.numLabel.mas_right);
        make.top.equalTo(self.numLabel);
        make.width.equalTo(self.expiryDayLabel);
          make.height.equalTo(self.numLabel);
    }];
    [self.expiryDayLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.teacherLabel.mas_right);
        make.top.equalTo(self.numLabel);
        make.right.equalTo(self.titleLabel);
        make.height.equalTo(self.numLabel);

    }];
    [self.detailLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.titleLabel);
        make.top.equalTo(self.numLabel.mas_bottom).offset(13);
        make.bottom.equalTo(self.contentView).offset(-vPadding + 1);
        
    }];
    
    
}
- (UILabel *)labelForSomeDetail
{
    UILabel *label = [UIView_Helper yLabel];
    label.font = [UIFont systemFontOfSize:13];
    label.textColor = [UIColor colorWithHexString:@"#6d7689"];
    return label;
}
- (void)setObject:(id)object
{
    [super setObject:object];
    
    self.titleLabel.text = [object valueForKey:@"title"];
    self.detailLabel.text = [object valueForKey:@"subtitle"];
    self.numLabel.text = [NSString stringWithFormat:@"学习人数：%@",[object valueForKey:@"num"]];
    self.teacherLabel.text = [NSString stringWithFormat:@"授课教师：%@",[object valueForKey:@"teacher"]];
    self.expiryDayLabel.text = [NSString stringWithFormat:@"有效期：%@",[[object valueForKey:@"expiryDay"]integerValue] <= 0 ?@"永久":[NSString stringWithFormat:@"%@天",[object valueForKey:@"expiryDay"]]];
}
@end


@interface ECUIVC_CDetailPage ()<UITableViewDelegate,UITableViewDataSource,WKNavigationDelegate,WKUIDelegate,UIScrollViewDelegate>
@property(nonatomic,strong)WKWebView *webView;
@property(nonatomic,strong)UIScrollView *scrollView;//可以放大缩小
@property(nonatomic,strong)NSMutableArray *dataSource;
@property(nonatomic,assign)CGFloat webHeight;
@end

@implementation ECUIVC_CDetailPage
@synthesize tableView = _tableView;
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    // Do any additional setup after loading the view.
    UIView *headerView = [[UIView alloc] initWithFrame:(CGRect){0, 0, kScreenWidth, TABLEVIEWCONTENT_OFFSET_Y}];
    headerView.backgroundColor = [UIColor clearColor];
    self.tableView.tableHeaderView = headerView;
    _tableView.tableFooterView = [UIView new];
    if (self.object) {
//        [self.webView loadHTMLString:self.object baseURL:nil];
        [self initDataSource];

    }
    self.view.backgroundColor = [UIColor clearColor];
}

- (void)setObject:(id)object
{
    [super setObject:object];
    
    if (self.viewLoaded) {
        [self initDataSource];
    }
}
-(void)initDataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    if (self.object  && self.dataSource.count <= 0) {
        NSString *result = [NSString stringWithFormat:@"<img style='display: block; max-width: %.0f'",kScreenWidth];
        id courseData = self.object;
        NSAttributedString *priceStr = [ECFormatHelper attributedStringForPromotionPrice:[courseData valueForKey:@"price"] decimal:2 smallFontSize:16];
        NSString *subtitle = [CYDataHelper isNull:[courseData valueForKey:@"subtitle"]]?@"还没有设置课程简介":[courseData valueForKey:@"subtitle"];
          NSString *title = [CYDataHelper isNull:[courseData valueForKey:@"title"]]?@"还没有设置课程标题":[courseData valueForKey:@"title"];
        NSString *teacher = [CYDataHelper isNull:[courseData valueForKey:@"teacher"]]?@"暂无":[courseData valueForKey:@"teacher"];
 
        NSString *line = @"<div style=\"height: 0.5px;margin: 15px 10px; line-height: 0.5px; background: #dbdbdb\"></div>";
        NSDictionary *dict = @{@"title":title,@"subtitle": subtitle,@"num":@([[courseData valueForKey:@"studentNum"]integerValue]),@"expiryDay":@([[courseData valueForKey:@"expiryDay"]integerValue]),@"teacher":teacher};
        // 这里判断 数据 空值的情况 <null>
//        NSString *cssStr = [NSString stringWithFormat:@"<html><style type=\"text/css\"> p{line-height: 24px!important;background-color: #fff;} img{max-width: %f !important;}</style>",width];
        NSString *header = @"<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/><meta  name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0\"/><meta name=\"apple-mobile-web-app-capable\" content=\"yes\"><meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black\"><link rel=\"stylesheet\" type=\"text/css\" /><style type=\"text/css\"> </style></head>";
        
        NSString *cssStr = [NSString stringWithFormat:@"<html>%@<body>",header];
        //内容简介
        NSString *brief = [CYDataHelper isNull:[courseData valueForKey:@"about"]]?@"":[courseData valueForKey:@"about"];
        if (brief.length > 0) {
            brief = [NSString stringWithFormat:@"%@%@",@"<div style=\"color: #454545; font-size: 18px; font:Arial; font-weight: 600;\">内容简介</div>",brief];
        }
        //适合对象
        NSString *audiences = [CYDataHelper isNull:[courseData valueForKey:@"audiences"]]?@"":[courseData valueForKey:@"audiences"];
        if (audiences.length) {
            audiences = [NSString stringWithFormat:@"%@%@%@",line,@"<div style=\"color: #454545; font-size: 18px; font:Arial; font-weight: 600;\">适合对象</div>",audiences];
        }
        //课时安排
        NSString *goals = [CYDataHelper isNull:[courseData valueForKey:@"goals"]]?@"":[courseData valueForKey:@"goals"];
        if (goals.length > 0) {
            goals = [NSString stringWithFormat:@"%@%@%@",line,@"<div style=\"color: #454545; font-size: 18px; font:Arial; font-weight: 600;\">课时安排</div>",goals];

        }
        //师资介绍
        NSString *teacherInfo = [CYDataHelper isNull:[courseData valueForKey:@"teacherInfo"]]?@"":[courseData valueForKey:@"teacherInfo"];
        if (teacherInfo.length > 0) {
            teacherInfo = [NSString stringWithFormat:@"%@%@%@",line,@"<div style=\"color: #454545; font-size: 18px; font:Arial; font-weight: 600;\">师资介绍</div>",teacherInfo];

        }
        // 课程详情
        NSString *content = [NSString stringWithFormat:@"%@%@%@%@",brief,audiences,goals,teacherInfo];
        // 把里面的图片标签遍历替换
        content = [content stringByReplacingOccurrencesOfString:@"<img" withString:result];
        NSString *detailHtml = [NSString stringWithFormat:@"%@%@%@",cssStr,
                               content,@"</body></html>"];
        [_dataSource addObjectsFromArray:@[priceStr,dict,detailHtml]];

        [self.webView loadHTMLString:detailHtml baseURL:nil];

        [self.tableView reloadData];
    }
}
-(WKWebView *)webView
{
    if (!_webView) {
//        WKWebViewConfiguration *webConfig = [[WKWebViewConfiguration alloc] init];
//        WKUserContentController *wkController = [[WKUserContentController alloc] init];
//        webConfig.userContentController = wkController;
//
////        // 自适应屏幕宽度js
////        NSString *jsStr = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
//        NSString *jsStr = @"function refreshView () {var imgstyle=document.getElementsByTagName('img'); for(var i=0;i<imgstyle.length;i++){ imgstyle[i].style.width='\(kScreenWidth)'+'px'; imgstyle[i].style.height = 'auto'; } return document.getElementById('myid').offsetTop;}";
//
//    WKUserScript *wkScript = [[WKUserScript alloc] initWithSource:jsStr injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
//        // 添加js调用
//        [wkController addUserScript:wkScript];
//        _webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:webConfig];
        _webView = [[WKWebView alloc]initWithFrame:self.view.bounds];
        _webHeight = _webView.height;
        _webView.backgroundColor = [UIColor whiteColor];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        _webView.scrollView.bounces = NO;
        _webView.scrollView.scrollEnabled = NO;
        _webView.scrollView.showsHorizontalScrollIndicator = NO;
        _webView.scrollView.delegate = self;

    }
    return _webView;
                
}

#pragma mark  ---  WKNavigationDelegate  ---
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{

    [_webView  evaluateJavaScript:@"document.body.offsetHeight"  completionHandler:^(id  _Nullable  result,  NSError  *  _Nullable  error)  {
        //  加20像素是为了预留出边缘
        CGFloat height = [result  doubleValue] + 20;
        //  设置一个高度属性，赋值后便于设置cell的高度
        _webHeight = MAX(self.webView.height, height);
        //  设置cell上子视图的frame，主要是高度
        _webView.frame = CGRectMake(0, 0, kScreenWidth, _webHeight);
        _scrollView.frame = CGRectMake(0, 0, kScreenWidth, height);
        _scrollView.contentSize = CGSizeMake(kScreenWidth, height);
        //  获取了高度之后，要更新webview所在的cell，其他的cell就不用更新了，这样能更节省资源
        [self.tableView  reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath  indexPathForRow:2  inSection:0], nil]  withRowAnimation:UITableViewRowAnimationNone];
    }];
//    [_webView  evaluateJavaScript:@"refreshView()"  completionHandler:^(id  _Nullable  result,  NSError  *  _Nullable  error)  {
//        //  加20像素是为了预留出边缘，这里可以随意
//        DLog(@"finish  : %@--- %@",result,error);
//        CGFloat  height  =  [result  doubleValue]  +  20;
//        //  设置一个高度属性，赋值后便于设置cell的高度
//        _webHeight = height;
//        //  设置cell上子视图的frame，主要是高度
//        _webView.frame  =  CGRectMake(0,  0,  kScreenWidth,  height);
//        //                                         _scrollView.frame  =  CGRectMake(0,  0,  kScreenWidth,  height);
//        //                                         _scrollView.contentSize  = CGSizeMake(kScreenWidth,  height);
//        //  获取了高度之后，要更新webview所在的cell，其他的cell就不用更新了，这样能更节省资源
//        //                                         [self.tableView  reloadRowsAtIndexPaths:[NSArray  arrayWithObjects:[NSIndexPath  indexPathForRow:2  inSection:0],  nil]  withRowAnimation:UITableViewRowAnimationNone];
//        [self.tableView reloadData];
//
//    }];

}

- (UITableView *)tableView
{
    if (!_tableView) {
//        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - TABBAR_FOOTER_HEIGHT-TABBAR_TITLE_HEIGHT - kNavHeight) style:UITableViewStylePlain];
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, self.view.height) style:UITableViewStylePlain];
        _tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight;

        [_tableView registerClass:[UITVCell_base class] forCellReuseIdentifier:@"cell"];
        [_tableView registerClass:[ECUITVCell_CDetail class] forCellReuseIdentifier:@"detailCell"];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        
    }
    return _tableView;
}
- (UIScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]init];
        _scrollView.delegate = self;
        _scrollView.zoomScale = 1;
        _scrollView.maximumZoomScale = 10;
        _scrollView.tag = 1000;
        [_scrollView addSubview:self.webView];
    }
    return _scrollView;
}
- (void)tableViewDidScroll:(tableViewDidScrollBlock)scrollBlock {
     //if (self.scrollBlock) {
        self.scrollBlock = scrollBlock;
//    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.tag == self.scrollView.tag) {
        return;
    }
    if (self.scrollBlock) {
        self.scrollBlock(scrollView.contentOffset.y);
    }
}
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    if (self.scrollView.tag == scrollView.tag) {
        return self.webView;

    }
    return nil;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITVCell_base *cell;
    if (indexPath.row == 0 || indexPath.row == 2) {
      cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    if (indexPath.row == 0) {
        cell.textLabel.attributedText = [self.dataSource objectAtIndex:0];//[ECFormatHelper attributedStringForOrginPrice:@"299.00" decimal:2 ];
    } else {
        [cell.contentView addSubview:self.scrollView];

    }
    } else {
        cell = [tableView dequeueReusableCellWithIdentifier:@"detailCell" forIndexPath:indexPath];
        cell.object = [self.dataSource objectAtIndex:1];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            cell.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10);
        }
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            cell.layoutMargins = UIEdgeInsetsZero;
        }

        if([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
            cell.preservesSuperviewLayoutMargins = false;

        }
    return cell;
    

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 50;
    }
    if (indexPath.row == 1) {
        return UITableViewAutomaticDimension;
    }
    if (indexPath.row == 2) {
        return _webHeight;
    }

    return kScreenHeight - kNavHeight - TABBAR_TITLE_HEIGHT - TABBAR_FOOTER_HEIGHT;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation -

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
